package com.agile.leetcode.concurrent.transmittable;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.alibaba.ttl.threadpool.TtlExecutors;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 *
 * TransmittableThreadLocal父线程移除后，子线程也获取不到的演示
 *
 * @author chenzhangkun
 * @ClassName TransmitThreadLocalSolution
 * @description: TODO
 * @date 2024年09月06日
 */
public class TransmitThreadLocalSolution {

	private static final TransmittableThreadLocal<String> transmittableThread = new TransmittableThreadLocal<>();

	public static void main(String[] args) throws Exception {
		transmittableThread.set("czk");
		ExecutorService executorService = TtlExecutors.getTtlExecutorService(Executors.newSingleThreadExecutor());
		executorService.submit(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
				System.out.println(transmittableThread.get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		TimeUnit.SECONDS.sleep(1);
		// 移除
		transmittableThread.remove();
		// 子线程再获取
		executorService.submit(() -> {
			try {
				TimeUnit.SECONDS.sleep(1);
				// 还能获取到
				System.out.println(transmittableThread.get());
			} catch (Exception e) {
				e.printStackTrace();
			}
		});
		TimeUnit.SECONDS.sleep(5);
		executorService.shutdown();
	}

}
